package com.xywy.bloodandroid.act;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.base.BaseActivity;
import com.xywy.bloodandroid.bean.AddNumData;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.ImageLoader;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.util.ImageLoader.ImageCallback;
import com.xywy.bloodandroid.util.JsonUtil;
import com.xywy.bloodandroid.util.MD5;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.vollery.GetRequest;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.VolleyManager;
import com.xywy.bloodandroid.widget.zrclistview.SimpleFooter;
import com.xywy.bloodandroid.widget.zrclistview.SimpleHeader;
import com.xywy.bloodandroid.widget.zrclistview.ZrcListView;
import com.xywy.bloodandroid.widget.zrclistview.ZrcListView.OnStartListener;

/**
 * 我的加号
 */
public class MyAddNumberActivity extends BaseActivity {

	protected static final int SUCCESS = 0;
	protected static final int FAIL = 1;
	public ImageLoader loader;
	private TextView middle_title;
	private RelativeLayout left_img;
	private ZrcListView lv_content; // 加号列表
	private List<AddNumData> datas = new ArrayList<AddNumData>(); // 获取服务器返回数据
	private int PageNum;
	private final int pagesize = 10;
	private int state = 0;// 订单状态 0:全部,1:等待就诊,2:等待审核(必填) 暂时没有筛选按钮
	private AddNumberAdapter adapter;
	private GetRequest<String> getRequest; // 网络请求
	private TextView tv_none_data; // 无数据展示

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.activity_add_number);
		lv_content = (ZrcListView) findViewById(R.id.lv_content);
		middle_title = (TextView) findViewById(R.id.middle_title);
		tv_none_data = (TextView) findViewById(R.id.tv_none_data);
		middle_title.setText("我的加号");
		left_img = (RelativeLayout) findViewById(R.id.left_img);
		lv_contentOption();
		loader = new ImageLoader();
		adapter = new AddNumberAdapter();
	}

	@Override
	protected void initListener() {
		tv_none_data.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				getdata(true);
			}
		});

		left_img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				MyAddNumberActivity.this.finish();
			}
		});
	}

	private void lv_contentOption() {
		// 设置默认偏移量，主要用于实现透明标题栏功能。（可选）
		// float density = getResources().getDisplayMetrics().density;
		// lv_content.setFirstTopOffset((int) (0 * density));

		// 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
		SimpleHeader header = new SimpleHeader(this);
		header.setTextColor(0xff0066aa);
		header.setCircleColor(0xff33bbee);
		lv_content.setHeadable(header);

		// 设置加载更多的样式（可选）
		SimpleFooter footer = new SimpleFooter(this);
		footer.setCircleColor(0xff33bbee);
		lv_content.setFootable(footer);

		// 设置列表项出现动画（可选）
		lv_content.setItemAnimForTopIn(R.anim.topitem_in);
		lv_content.setItemAnimForBottomIn(R.anim.bottomitem_in);

		// 下拉刷新事件回调（可选）
		lv_content.setOnRefreshStartListener(new OnStartListener() {
			@Override
			public void onStart() {
				PageNum = 1;
				getdata(true);
			}
		});

		// 加载更多事件回调（可选）
		lv_content.setOnLoadMoreStartListener(new OnStartListener() {
			@Override
			public void onStart() {
				PageNum++;
				getdata(false);
			}
		});
		// lv_content.refresh(); // 主动下拉刷新

	}

	@Override
	protected void onResume() {
		super.onResume();
		PageNum = 1;
		getdata(true);
	}

	@Override
	protected void initData() {
	}

	/**
	 * 
	 * @param b
	 *            true 刷新 false 加载
	 */
	private void getdata(final boolean b) {
		String sign = null;
//		String testUserId = "8519661";
		String testUserId = User.getInstance(context).getUserid();
		try {

			sign = MD5.md5s(Constants.Sign + Constants.tag);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String url = "http://api.wws.xywy.com/index.php?act=zhuanjia&fun=Plus&tag="
				+ Constants.tag
				+ "&sign="
				+ sign
				+ "&user_id="
				+ User.getInstance(this).getUserid() // testUserId
				+ "&state="
				+ state
				+ "&pagesize="
				+ pagesize
				+ "&PageNum="
				+ PageNum;

		getRequest = new GetRequest<String>(url, String.class,
				new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						UIUtil.DissDialog(context, waittingDialog);
						Message msg = Message.obtain();
						msg.what = FAIL;
						msg.obj = false;
						handler.sendMessage(msg);
					}

					@SuppressWarnings("unchecked")
					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(context, waittingDialog);
						try {
							if (b) {
								datas.clear();
							}

							JSONObject object = new JSONObject(response);
							if (object.getInt("code") == 10000) {
								String data = object.getString("data");

								List<AddNumData> templist = (List<AddNumData>) JsonUtil.parseJsonToList(
										new JSONObject(data).getString("data"),
										new TypeToken<List<AddNumData>>() {
										}.getType());

								if (null == templist || templist.size() < 1) {
									showToast("您还未加号");
									return;
								} else {
									datas.addAll(templist);
								}

								if (b) {
									lv_content.setAdapter(adapter);
								} else {
									adapter.notifyDataSetChanged();
								}
								Message msg = Message.obtain();
								msg.what = SUCCESS;
								msg.obj = true;
								handler.sendMessage(msg);
							} else {
								showToast(object.getString("msg"));
								Message msg = Message.obtain();
								msg.what = FAIL;
								msg.obj = false;
								handler.sendMessage(msg);
							}

						} catch (JSONException e) {
							Message msg = Message.obtain();
							msg.what = FAIL;
							msg.obj = false;
							handler.sendMessage(msg);
							e.printStackTrace();
						}
					}
				});

		getRequest.setIsParseJson(false);
		if (b) {
			executeRequest(getRequest);
		} else {
			VolleyManager.addRequest(getRequest, this);
		}

	}

	/**
	 * 处理网络请求后数据
	 */
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:

				lv_content.setVisibility(View.VISIBLE);
				tv_none_data.setVisibility(View.GONE);

				UIUtil.DissDialog(context, waittingDialog);
				if ((Boolean) msg.obj) {
					lv_content.setRefreshSuccess("刷新成功");
					lv_content.startLoadMore();
				} else {
					lv_content.setRefreshFail("加载成功");
				}
				break;
			case FAIL:
				UIUtil.DissDialog(context, waittingDialog);
				if ((Boolean) msg.obj) {
					lv_content.setLoadMoreSuccess();
				} else {
				}
				break;
			}
		};
	};

	@Override
	protected void onStop() {
		super.onStop();
		if (getRequest != null) {
			VolleyManager.cancelRequest(getRequest);
		}
	}

	/**
	 * List 适配器
	 */
	class AddNumberAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return datas.size();
		}

		@Override
		public Object getItem(int arg0) {
			return datas.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup arg2) {
			ViewHolder holder;
			if (view == null) {
				holder = new ViewHolder();
				view = View.inflate(MyAddNumberActivity.this,
						R.layout.item_add_num, null);
				holder.ll_rootview = (LinearLayout) view
						.findViewById(R.id.ll_rootview);
				holder.iv_avatar = (ImageView) view
						.findViewById(R.id.iv_avatar);
				holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
				holder.tv_doctor_time = (TextView) view
						.findViewById(R.id.tv_doctor_time);
				holder.tv_date_state = (TextView) view
						.findViewById(R.id.tv_date_state);
				holder.tv_refuse_reason = (TextView) view
						.findViewById(R.id.tv_refuse_reason);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}

			Drawable cachedImage = loader.loadDrawable(datas.get(position)
					.getExpert_pic(), holder.iv_avatar, new ImageCallback() {

				@Override
				public void imageLoaded(Drawable imageDrawable,
						ImageView imageView, String imageUrl) {
					if (imageView != null && imageDrawable != null) {
						imageView.setBackgroundDrawable(imageDrawable);
					}
				}
			});
			if (cachedImage == null) {
				holder.iv_avatar.setBackgroundResource(R.drawable.head);
			} else {
				holder.iv_avatar.setBackgroundDrawable(cachedImage);
			}

			holder.tv_name.setText("专家姓名：" + datas.get(position).getExpert());
			holder.tv_doctor_time.setText("预约就诊时间："
					+ datas.get(position).getTodate());
			holder.tv_date_state.setText("预约状态:"
					+ datas.get(position).getExpert());

			int state = Integer.parseInt(datas.get(position).getState());
			String text = getStateStr(state);
			holder.tv_date_state.setText(text);
			if (datas.get(position).getReason() != null
					|| datas.get(position).getReason().length() > 0) {
				holder.tv_refuse_reason.setVisibility(View.VISIBLE);
				holder.tv_refuse_reason
						.setText(datas.get(position).getReason());
			} else {
				holder.tv_refuse_reason.setVisibility(View.GONE);
			}
			holder.ll_rootview.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(MyAddNumberActivity.this,
							MyAddNumberDetailsActivity.class);
					intent.putExtra("data", datas.get(position));
					startActivity(intent);
				}
			});
			return view;
		}

		/**
		 * 获取当前的状态 订单状态 (1:待审核 2:等待就诊 3:未通过审核 4:预约取消 5:成功就诊 6:爽约 7:取消就诊)
		 * 
		 * @param state
		 * @return
		 */
		private String getStateStr(int state) {
			switch (state) {
			case 1:
				return "待审核";
			case 2:
				return "等待就诊";
			case 3:
				return "未通过审核";
			case 4:
				return "预约取消";
			case 5:
				return "成功就诊";
			case 6:
				return "爽约";
			case 7:
				return ":取消就诊";
			}
			return null;
		}

		private class ViewHolder {
			LinearLayout ll_rootview;
			ImageView iv_avatar;
			TextView tv_name;
			TextView tv_doctor_time;
			TextView tv_date_state;
			TextView tv_refuse_reason;

		}

	}

}
